<template>
  <div>
    <Activity
      :CustomerValue="CustomerValue"
      @getCustomerValue="getCustomerValue"
      @closeDrawer="closeDrawer"
      @prev="prev"
      @next="next"
      @refreshPage="emit('refreshData')"
      :tagMap="tagMap"
      :isLoad="isLoading"
      :isPool="isPool"
      :validateWrite="validateWrite"
      :validateOwnerUser="validateOwnerUser"
      :moduleOption="moduleOption"
    />
    <!-- 详细资料 -->
    <Details v-if="selectTag == 1" :CustomerValue="CustomerValue" />
    <SystemCustomer v-if="selectTag == 1" :CustomerValue="CustomerValue" />
    <!-- ai摘要 -->
    <AiSummary v-if="selectTag == 11" :clueValue="CustomerValue" />
    <!-- 状态 -->
    <StatusCustomer
      @getCustomerValue="getCustomerValue"
      v-if="selectTag == 0"
      :CustomerValue="CustomerValue"
    />
    <!-- 跟进记录 -->
    <FlowUp v-if="selectTag == 0" :clueValue="CustomerValue" :bizType="BizTypeEnum.CRM_CUSTOMER" />
    <!-- 操作日志 -->
    <Log
      v-if="selectTag == 10"
      :clueValue="CustomerValue"
      :id="CustomerValue.id"
      :bizType="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 团队成员 -->
    <teamMembers
      v-if="selectTag == 3"
      :bizId="CustomerValue.id"
      :bizType="BizTypeEnum.CRM_CUSTOMER"
      :showAction="true"
    />
    <!-- 联系人 -->
    <ContactList
      v-if="selectTag == 2"
      :biz-id="CustomerValue.id"
      :customer-id="CustomerValue.id"
      :biz-type="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 商机 -->
    <BusinessList
      v-if="selectTag == 5"
      :biz-id="CustomerValue.id"
      :customer-id="CustomerValue.id"
      :biz-type="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 合同 -->
    <ContractList
      v-if="selectTag == 6"
      :biz-id="CustomerValue.id"
      :customer-id="CustomerValue.id"
      :biz-type="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 回款-->
    <ReceivableList v-if="selectTag == 7" ref="receivableListRef" :customer-id="CustomerValue.id" />
    <!-- 回款计划 -->
    <ReceivablePlanList
      v-if="selectTag == 9"
      :customer-id="CustomerValue.id"
      @create-receivable="createReceivable"
    />
    <!-- 企微-->
    <Wecom
      v-if="selectTag == 8"
      :customer="CustomerValue"
      @showWeCom="showWeCom"
      :wecomFollowUserList="wecomFollowUserList"
      :userItem="userItem"
      :isPool="isPool"
    />
  </div>
  <Dialog v-model="dialogVisible" title="关联企业微信" width="1400">
    <el-table
      :data="gridData"
      @selection-change="handleSelectionChange"
      ref="myTable"
      @select="selectTable"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="客户名称" prop="name">
        <template #default="scope">
          <div class="flex items-center">
            <span v-if="scope.row.type == 1" class="block w-25px h-25px mr-6px">
              <svg
                t="1721110751169"
                class="icon w-100% h-100%"
                viewBox="0 0 1229 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="8691"
                width="200"
                height="200"
              >
                <path
                  d="M702.72 849.92c-76.8 30.72-158.72 35.84-240.64 30.72-35.84-5.12-71.68-10.24-107.52-20.48-5.12 0-10.24 0-15.36 5.12-46.08 20.48-92.16 46.08-133.12 66.56-15.36 10.24-30.72 10.24-46.08 0s-15.36-25.6-15.36-46.08c10.24-35.84 10.24-71.68 15.36-107.52 0-5.12-5.12-10.24-5.12-15.36-51.2-51.2-92.16-102.4-122.88-168.96-51.2-122.88-40.96-245.76 30.72-358.4C134.4 112.64 247.04 46.08 380.16 15.36S641.28 0 764.16 61.44c112.64 56.32 194.56 143.36 230.4 266.24 15.36 46.08 20.48 92.16 15.36 138.24-25.6-25.6-56.32-30.72-87.04-15.36 0-30.72 0-61.44-10.24-92.16-20.48-71.68-61.44-128-112.64-174.08-87.04-71.68-194.56-102.4-307.2-102.4-117.76 10.24-220.16 51.2-302.08 133.12-66.56 66.56-102.4 148.48-97.28 245.76 5.12 81.92 40.96 148.48 92.16 204.8l40.96 40.96c20.48 15.36 25.6 30.72 15.36 51.2-5.12 20.48-10.24 46.08-15.36 66.56 0 5.12-5.12 10.24 0 10.24 5.12 5.12 10.24 0 10.24 0 25.6-15.36 56.32-30.72 81.92-51.2 15.36-10.24 30.72-10.24 51.2-5.12 87.04 25.6 179.2 25.6 266.24 0 5.12 0 10.24-5.12 10.24 5.12 10.24 30.72 25.6 51.2 56.32 66.56z"
                  fill="#0082EF"
                  p-id="8692"
                ></path>
                <path
                  d="M1214.72 747.52c0 35.84-25.6 61.44-56.32 66.56-51.2 10.24-92.16 30.72-128 66.56-10.24 10.24-15.36 10.24-25.6 5.12-5.12-5.12-5.12-15.36 0-25.6 35.84-35.84 56.32-81.92 66.56-128 5.12-35.84 40.96-56.32 76.8-56.32 40.96 5.12 66.56 35.84 66.56 71.68z"
                  fill="#0081EE"
                  p-id="8693"
                ></path>
                <path
                  d="M953.6 1024c-35.84 0-66.56-25.6-71.68-56.32-5.12-51.2-30.72-92.16-66.56-122.88-5.12-5.12-10.24-10.24-5.12-20.48 5.12-15.36 15.36-15.36 25.6-10.24 10.24 5.12 15.36 15.36 20.48 20.48 30.72 25.6 66.56 40.96 102.4 46.08 35.84 5.12 61.44 40.96 56.32 76.8 5.12 35.84-25.6 66.56-61.44 66.56z"
                  fill="#FA6202"
                  p-id="8694"
                ></path>
                <path
                  d="M682.24 757.76c0-35.84 20.48-61.44 56.32-71.68 51.2-10.24 92.16-30.72 128-66.56 10.24-10.24 20.48-10.24 25.6 0 5.12 5.12 5.12 15.36-5.12 25.6-30.72 30.72-51.2 66.56-61.44 112.64 0 5.12 0 15.36-5.12 20.48-10.24 35.84-40.96 56.32-76.8 51.2-35.84-5.12-61.44-35.84-61.44-71.68z"
                  fill="#FECD00"
                  p-id="8695"
                ></path>
                <path
                  d="M1035.52 578.56c15.36 30.72 30.72 56.32 51.2 76.8 10.24 10.24 10.24 20.48 5.12 25.6-5.12 10.24-15.36 10.24-25.6 0-25.6-30.72-61.44-51.2-97.28-61.44-10.24-5.12-20.48-5.12-30.72-5.12-20.48-5.12-40.96-15.36-46.08-40.96-10.24-25.6-10.24-51.2 10.24-71.68 20.48-25.6 46.08-30.72 71.68-25.6 25.6 10.24 46.08 25.6 51.2 56.32 0 15.36 5.12 30.72 10.24 46.08z"
                  fill="#2CBD00"
                  p-id="8696"
                ></path>
              </svg>
            </span>
            <span v-if="scope.row.type == 2" class="block w-25px h-25px mr-6px">
              <svg
                t="1721110793630"
                class="icon w-100% h-100%"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="9756"
                width="200"
                height="200"
              >
                <path
                  d="M337.387283 341.82659c-17.757225 0-35.514451 11.83815-35.514451 29.595375s17.757225 29.595376 35.514451 29.595376 29.595376-11.83815 29.595376-29.595376c0-18.49711-11.83815-29.595376-29.595376-29.595375zM577.849711 513.479769c-11.83815 0-22.936416 12.578035-22.936416 23.6763 0 12.578035 11.83815 23.676301 22.936416 23.676301 17.757225 0 29.595376-11.83815 29.595376-23.676301s-11.83815-23.676301-29.595376-23.6763zM501.641618 401.017341c17.757225 0 29.595376-12.578035 29.595376-29.595376 0-17.757225-11.83815-29.595376-29.595376-29.595375s-35.514451 11.83815-35.51445 29.595375 17.757225 29.595376 35.51445 29.595376zM706.589595 513.479769c-11.83815 0-22.936416 12.578035-22.936416 23.6763 0 12.578035 11.83815 23.676301 22.936416 23.676301 17.757225 0 29.595376-11.83815 29.595376-23.676301s-11.83815-23.676301-29.595376-23.6763z"
                  fill="#28C445"
                  p-id="9757"
                ></path>
                <path
                  d="M510.520231 2.959538C228.624277 2.959538 0 231.583815 0 513.479769s228.624277 510.520231 510.520231 510.520231 510.520231-228.624277 510.520231-510.520231-228.624277-510.520231-510.520231-510.520231zM413.595376 644.439306c-29.595376 0-53.271676-5.919075-81.387284-12.578034l-81.387283 41.433526 22.936416-71.768786c-58.450867-41.433526-93.965318-95.445087-93.965317-159.815029 0-113.202312 105.803468-201.988439 233.803468-201.98844 114.682081 0 216.046243 71.028902 236.023121 166.473989-7.398844-0.739884-14.797688-1.479769-22.196532-1.479769-110.982659 1.479769-198.289017 85.086705-198.289017 188.67052 0 17.017341 2.959538 33.294798 7.398844 49.572255-7.398844 0.739884-15.537572 1.479769-22.936416 1.479768z m346.265896 82.867052l17.757225 59.190752-63.630058-35.514451c-22.936416 5.919075-46.612717 11.83815-70.289017 11.83815-111.722543 0-199.768786-76.947977-199.768786-172.393063-0.739884-94.705202 87.306358-171.653179 198.289017-171.65318 105.803468 0 199.028902 77.687861 199.028902 172.393064 0 53.271676-34.774566 100.624277-81.387283 136.138728z"
                  fill="#28C445"
                  p-id="9758"
                ></path>
              </svg>
            </span>
            <span
              @click="goDetail(scope.row)"
              class="cursor-pointer block w-126px text-left break-word color-#0052cc"
              >{{ scope.row.name }}</span
            >
          </div>
        </template>
      </el-table-column>

      <el-table-column label="所在群聊" align="center" prop="chatGroupList">
        <template #default="scope">
          <span class="color-#0052cc cursor-pointer" v-if="scope.row.chatGroupList.length > 1"
            >{{ scope.row.chatGroupList[0]?.name }}等{{
              scope.row.chatGroupList.length
            }}个群聊</span
          >
          <span class="color-#0052cc cursor-pointer" v-if="scope.row.chatGroupList.length <= 1">{{
            scope.row.chatGroupList[0]?.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户所在企业" align="center" prop="corpName" show-overflow-tooltip />
      <el-table-column
        label="客户所在企业主体"
        align="center"
        prop="corpFullName"
        show-overflow-tooltip
      />
      <el-table-column label="客户职位" align="center" prop="positionName" width="150px" />
      <el-table-column label="客户备注" align="center" prop="remark" width="150px" />
      <el-table-column label="客户描述" align="center" prop="description" width="150px" />
      <el-table-column label="备注的手机号" align="center" prop="remarkMobiles" width="150px" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180px"
        :formatter="dateFormatter"
      />
    </el-table>
    <Pagination
      :total="totals"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <div style="margin-top: 100px; text-align: right">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confrimWeCom"> 确 定 </el-button>
    </div>
  </Dialog>
</template>

<script setup>
import { dateFormatter } from '@/utils/formatTime'
import { customFieldHeadList } from '@/api/crm/module/index'
import * as CustomerApi from '@/api/crm/customer'
import * as customerTagApi from '@/api/crm/customerTagConfig/index'
import * as PermissionApi from '@/api/crm/permission'
import { BizTypeEnum } from '@/api/crm/permission'
import { useUserStoreWithOut } from '@/store/modules/user'
import FlowUp from '@/views/crm/clue/detail/flowUp.vue'
import Log from '@/views/crm/components/log/index.vue'
import teamMembers from '@/views/crm/components/teamMembers/index.vue'
import ContactList from '@/views/crm/contact/components/newContactList.vue'
import BusinessList from '@/views/crm/business/components/newBusinessList.vue'
import ContractList from '@/views/crm/contract/components/newContractList.vue'
import ReceivableList from '@/views/crm/receivable/components/newReceivableList.vue'
import ReceivablePlanList from '@/views/crm/receivable/plan/components/newReceivablePlanList.vue'
import * as weCustomerApi from '@/api/wecom/customer/index'
import { getWeCustomerPage } from '@/api/wecom/customer/index'
import Wecom from './newWeCome.vue'
import StatusCustomer from './status.vue'
import Details from './details.vue'
import SystemCustomer from './system.vue'
import Activity from './activity.vue'
import AiSummary from '@/views/crm/clue/detail/aiSummary.vue'

const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})

const props = defineProps({
  selectTag: Number,
  id: String,
  nowIds: Array,
  moduleOption: Array
})
const emit = defineEmits(['setDrawer', 'refreshData'])
const customerId = ref('')
const CustomerValue = ref({})
const tagMap = ref([])
const isLoading = ref(false)

const teamMembersList = ref([])
const loading = ref(false)
/** 查询列表 */
const getTeamMembers = async () => {
  loading.value = true
  try {
    const data = await PermissionApi.getPermissionList({
      bizType: BizTypeEnum.CRM_CUSTOMER,
      bizId: props.id
    })
    teamMembersList.value = data
  } finally {
    loading.value = false
  }
}
/** 从回款计划创建回款 */
const receivableListRef = ref()
const createReceivable = (planData) => {
  receivableListRef.value?.createReceivable(planData)
}
/**客户的详情*/
const getCustomerValue = async () => {
  try {
    isLoading.value = true
    const res = await CustomerApi.getCustomer(customerId.value)
    const filedResult = await customFieldHeadList({
      moduleId: customerId.value,
      tableType: '2'
    })
    if (filedResult) {
      res.detailFiled = filedResult.filter((item) => item.isShow == 1)
    }
    const results = await CustomerApi.getCustomerTag({ ids: [customerId.value] })
    res.labelList = results[customerId.value] || []
    CustomerValue.value = res
    if (CustomerValue.value.weCustomerId) getWeComDetail(CustomerValue.value.weCustomerId)
  } finally {
    isLoading.value = false
  }
}
/**标签列表*/
const getTagList = async () => {
  const { list } = await customerTagApi.getCustomerTagPage()
  tagMap.value = list
}
/**上一条*/
const prev = () => {
  const index = props.nowIds.indexOf(customerId.value) - 1
  if (props.nowIds[index]) {
    customerId.value = props.nowIds[index]
    getCustomerValue()
    getTeamMembers()
  } else {
    ElMessage.error('没有更多了')
  }
}
/**下一条*/
const next = () => {
  const index = props.nowIds.indexOf(customerId.value) + 1
  if (props.nowIds[index]) {
    customerId.value = props.nowIds[index]
    getCustomerValue()
    getTeamMembers()
  } else {
    ElMessage.error('没有更多了')
  }
}
watch(
  () => props.id,
  (val) => {
    if (val) {
      customerId.value = val
      getCustomerValue()
      getTeamMembers()
      getTagList()
    }
  },
  { deep: true, immediate: true }
)
/**关闭*/
const closeDrawer = () => {
  emit('setDrawer')
}
// 校验负责人权限和编辑权限
const validateOwnerUser = ref(false)
const validateWrite = ref(false)
const isPool = ref(false)
const userStore = useUserStoreWithOut()

// const customerHeader = ref(null)
const dialogVisible = ref(false)
const gridData = ref([])
const totals = ref(0)
// 显示关联企微
const showWeCom = async () => {
  if (isPool.value) return
  const { list, total } = await getWeCustomerPage(queryParams.value)
  gridData.value = list
  totals.value = total
  dialogVisible.value = true
}
const wecomFollowUserList = ref([])
const userItem = ref({})
/** 查询企微客户详情*/
const getWeComDetail = async (id) => {
  const data = await weCustomerApi.getWeCustomerId(id)
  userItem.value = data
  if (data && data.followUserList) {
    wecomFollowUserList.value = data.followUserList
  } else {
    wecomFollowUserList.value = []
  }
}
const myTable = ref(null)
/**只能选择一条*/
const handleSelectionChange = (selectVal) => {
  selectVal.map((row, index) => {
    if (selectVal.length <= 1) {
      return
    }
    myTable.value.toggleRowSelection(row, false)
    if (index === selectVal.length - 1) {
      myTable.value.toggleRowSelection(row, true)
    }
  })
}
const changItem = ref(null)
// 表格选中的数据
const selectTable = (val) => {
  if (val.length) {
    changItem.value = val[val.length - 1]
  } else {
    changItem.value = null
  }
}
// 确定提交
const confrimWeCom = async () => {
  if (changItem.value) {
    dialogVisible.value = false
    const data = await CustomerApi.updateCustomerWeCom({
      id: props.id,
      weCustomerId: changItem.value.externalUserId
    })
    if (data) {
      ElMessage.success('操作成功')
      getWeComDetail(props.id)
    }
  } else {
    ElMessage.warning('请选择关联的企业微信')
  }
}
watch(
  () => teamMembersList.value,
  (newArr) => {
    isPool.value = false
    validateOwnerUser.value = false
    validateWrite.value = false
    if (newArr.length > 0) {
      isPool.value = !newArr.some((item) => item.level === PermissionApi.PermissionLevelEnum.OWNER)
      const userId = userStore.getUser?.id
      newArr
        .filter((item) => item.userId === userId)
        .forEach((item) => {
          if (item.level === PermissionApi.PermissionLevelEnum.OWNER) {
            validateOwnerUser.value = true
            validateWrite.value = true
          } else if (item.level === PermissionApi.PermissionLevelEnum.WRITE) {
            validateWrite.value = true
          }
        })
    } else {
      isPool.value = true
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<style lang="scss" scoped></style>
